package sample;

import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.scene.layout.GridPane;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
import javafx.stage.DirectoryChooser;
import javafx.stage.Stage;
import utils.CommonComponent;

import java.io.*;
import java.util.Objects;

public class SDKReplaceTest {
    //新的窗口
    Stage secondStage;
    //sdk目录
    TextField sdkPath;
    //android目录
    TextField androidPath;

    public SDKReplaceTest(Stage secondStage) {
        this.secondStage = secondStage;
    }

    public void startShow() {
        GridPane grid = new GridPane();
        grid.setAlignment(Pos.CENTER);
        grid.setHgap(10);
        grid.setVgap(10);
        grid.setPadding(new Insets(25, 25, 25, 25));
        secondStage.setTitle("测试新的SDK操作");
        secondStage.setScene(new Scene(grid,500,350));
        secondStage.setX(600);
        initUILayout(grid);
        secondStage.show();
    }
    //初始化布局
    private void initUILayout(GridPane grid) {
        Text title=new Text("替换sdk so文件");
        grid.add(title,0,0);
        createRowUiLayout(grid,"选择sdk目录","...",1);
        createRowUiLayout(grid,"选择Android Project","...",2);
        Button replaceSdk=new Button("替换");
        //设置Android默认项目路径
        androidPath.setText("/Users/feihu/Downloads/androidProject/SDKTestMySelf");
        replaceSdk.setOnMouseClicked((e)->{
            if(checkEmpty(sdkPath) && checkEmpty(androidPath)){
                CommonComponent.errorAlert("ERROR!","选择信息不能为空！");
                return;
            }
            replaceSdkHandle();
            CommonComponent.warningAlert("SUCCESS","替换完成！");
        });
        grid.add(replaceSdk,0,3);

    }

    private void replaceSdkHandle() {
        File sdkPathDirectory=new File(sdkPath.getText());
        File androidPahDirectory=new File(androidPath.getText()+"/app/src/jniLibs");
        String[] directories=androidPahDirectory.list();
        if(sdkPathDirectory.isDirectory()){
            String path;
            //查找文件
            if(!(path=searchDirectory(sdkPathDirectory,"Android")).equals("")){
                    String tempPath;
                    for(String directory:directories){
                        if(directory.equals(".DS_Store")){
                            continue;
                        }
                        tempPath=searchDirectory(new File(sdkPathDirectory+"/Android"),directory);
                        //sdk找到了特定架构的目录
                        File sourceArchitecture=new File(tempPath);
                        tempPath=searchDirectory(androidPahDirectory,directory);
                        File targetArchitecture=new File(tempPath);
                        System.out.println(sourceArchitecture.getAbsolutePath()+"    "+targetArchitecture.getAbsolutePath());
                        copyFile(sourceArchitecture.listFiles()[0],targetArchitecture.listFiles()[0]);
                    }
            }else{
                CommonComponent.errorAlert("ERROR","找不到Android文件夹的存在！");
            }


        }else{
            CommonComponent.errorAlert("ERROR","'选择sdk目录'栏不是一个目录");
        }
    }

    /**
     * 移动 特定文件到某个路径
     * @param sourceFile
     * @param targetFile
     */
    private void moveFile(File sourceFile,File targetFile){
        if(targetFile.exists()){
            targetFile.delete();
        }
        sourceFile.renameTo(targetFile);
    }

    private void copyFile(File sourceFile,File targetFile){
        if(targetFile.exists()){
            targetFile.delete();
        }
        try {
            BufferedOutputStream bo=new BufferedOutputStream(new FileOutputStream(targetFile));
            BufferedInputStream bi=new BufferedInputStream(new FileInputStream(sourceFile));
            byte[] bytes=new byte[2048];
            while(bi.read(bytes)!=-1){
                bo.write(bytes);
            }
            System.out.println("复制文件成功： 来自----"+sourceFile.getAbsolutePath());
        } catch (FileNotFoundException e) {
            CommonComponent.errorAlert("ERROR!","找不到需要复制的文件："+sourceFile.getName());
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 查找文件名是否存在
     * @param file
     * @return
     */
    private String searchDirectory(File file,String fileName) {
        for(File target: Objects.requireNonNull(file.listFiles())){
            if(target.getName().equals(fileName)){
                return target.getAbsolutePath();
            }
        }
        return "";
    }

    /**
     * @Description 以label：textField：button形式创建以行为目标的ui布局
     * @param grid
     * @param label
     * @param button 按钮的名称
     * @param row   在第几行显示
     */
    private void createRowUiLayout(GridPane grid,String label,String button,int row){
            Text text=new Text(label);
            text.setFont(Font.font("Tahoma", FontWeight.LIGHT, 12));
            TextField textField=new TextField();
            switch (row){
                case 1:
                    sdkPath=textField;
                    break;
                case 2:
                    androidPath=textField;
                    break;
            }
            Button selectDirectory=new Button(button);
            selectDirectory.setOnMouseClicked((e)->{
                DirectoryChooser directoryChooser=new DirectoryChooser();
                directoryChooser.setTitle("选择目录");
                File directory=directoryChooser.showDialog(secondStage);
                textField.setText(directory.getAbsolutePath());
            });
            grid.add(text,0,row);
            grid.add(textField,1,row);
            grid.add(selectDirectory,2,row);
    }
    private boolean checkEmpty(TextField textField){
        if(textField.getText().isEmpty()){
            return true;
        }else{
            return false;
        }
    }

}
